#!/usr/bin/python
#coding=utf-8

from app.lib import BaseHandler
from utils.common import auth
from utils.common import check_token 
from utils.common import render
from utils.common import set_navbar 
from web.session import Session
from model.product import ProductManager
from model.order import OrderManager
from model.order import OrderState 
from igor import logging

class Buy(BaseHandler):

    @auth
    @check_token
    def post(self, req, resp):
        pid = req.args.get('pid', [''])[0]
        price = req.args.get('price', [''])[0]
        sess = Session(req)
        user = sess['user']
        omanager = OrderManager()
        ret = omanager.buy(pid, user, price)
        logging.log('buy state=%s' % ret)
        if ret == OrderState.OK:
            return resp.redirect('/account/buy')
        elif ret == OrderState.LESS_MONEY:
            return resp.repond('余额不够，请充值先') 
        elif ret == OrderState.PRICE_UPDATED:
            return resp.repond('价格已经更新，请刷新') 
        else:
            return resp.redirect('/error') 
        

class Order(BaseHandler):

    @auth
    def get(self, req, resp):
        session = Session(req)
        user = session.get('user')
        token = session.get('token')
        patterns = set_navbar(req)
        pid = req.args.get('pid', [''])[0]
        pmanager = ProductManager()
        product = pmanager.query_by_id(pid)
        if product and user:
            patterns.update({'user': user, 'item': product,
                'order_price': product.price, 'token':token})
        body = render('orderlist.html', patterns)
        return resp.respond(body)
        
        

    


